package com.ganzalang.gmall.learning.netty.nio.zerocopy;

import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @description: NIO的服务端
 * @author: Ganzalang
 * @Date 2021/7/15 15:21
 */
@Slf4j
public class NewIOServer {

    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        InetSocketAddress address = new InetSocketAddress(7002);
        serverSocket.bind(address);
        // 创建Buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();

            int readCount = 0;
            while (-1 != readCount) {
                try {
                    readCount = socketChannel.read(byteBuffer);
                } catch (Exception e) {
//                    e.printStackTrace();
                    break;
                }
                // 将buffer的position、mark作废
                byteBuffer.rewind();
            }
        }
    }
}
